import React, {  Component } from 'react';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';

import { List, InputItem, WingBlank, WhiteSpace, Button } from 'antd-mobile';
import Logo from '../../components/logo';
import { actionCreators } from '../../otherReducer/user';
import { HintDiv } from '../register/style';

class Login extends Component {

    constructor(props) {
        super(props);
        this.state = {
            user: '',
            password: ''
        }
        this.toRegister = this.toRegister.bind(this);
        this.handleLogin = this.handleLogin.bind(this);
    }

    handleInfoChange(key, e) {
        this.setState({
            [key]: e
        })
    }

    handleLogin() {
        this.props.login(this.state);
    }

    render() {
        const isRedirect = this.props.redirectTo;
        const hintMsg = this.props.msg;
        return (
            <div> 
                {
                    isRedirect ? <Redirect to={isRedirect} /> : null
                }
                <Logo />
                <WingBlank>
                    {
                        hintMsg ? <HintDiv>{hintMsg}</HintDiv> : null 
                    }
                    <List>
                        <InputItem onChange={val=>this.handleInfoChange('user', val)}>用户名</InputItem>
                        <InputItem
                            type="password"
                            onChange={val=>this.handleInfoChange('password', val)}
                        >密码</InputItem>
                    </List>
                    <WhiteSpace />
                    <Button type="primary" onClick={this.handleLogin}>登录</Button>
                    <WhiteSpace />
                    <Button type="primary" onClick={this.toRegister}>注册</Button>
                </WingBlank>
            </div>
        )
    }

    toRegister() {
        this.props.removeErrorMsg();
        this.props.history.push('/register');
    }
};

const mapStateToProps = (state) => ({
    redirectTo: state.getIn(['user', 'redirectTo']),
    msg: state.getIn(['user', 'msg'])    
});

const mapDispatchToProps = (dispatch) => ({
    login(userMsg) {
        dispatch(actionCreators.login(userMsg));
    },
    removeErrorMsg() {
        dispatch(actionCreators.errorMsg(''));
    }
})

export default connect(mapStateToProps, mapDispatchToProps)(Login);